package br.com.frbb.ugvbr.image;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.neuroph.contrib.imgrec.ImageRecognitionPlugin;
import org.neuroph.contrib.imgrec.image.ImageAndroid;
import org.neuroph.contrib.imgrec.image.ImageFactory;
import org.neuroph.contrib.imgrec.image.ImageType;
import org.neuroph.core.NeuralNetwork;

import android.graphics.Bitmap;
import android.util.Log;

public class ImageProcessor {

	private final String RECOGNITION_TAG = this.getClass().getName() + ".IMAGE_RECOGNITION";
	
	private InputStream nnetFile;
	private NeuralNetwork nnet;
    private ImageRecognitionPlugin imageRecognition;
    
    ImageProcessor(InputStream nnetFile) {
    	this.nnetFile = nnetFile;
        new Thread(null, loadRNA, "loadRNA", 128000).start();
    }
    
    public String recognize(Bitmap bitmap) {
    	ImageAndroid image;
    	String answer = null;
    	
    	// Caso a rede neural esteja carregada
    	if(imageRecognition != null) {
    		
	    	// Cria arquivo de imagem para reconhecimento
    		image = (ImageAndroid)ImageFactory.createImage(bitmap.getWidth(), bitmap.getHeight(), ImageType.ANDROID_TYPE_RGB_565);
	    	image.setBitmap(bitmap);
			
	    	// Resgata resposta
	    	HashMap<String, Double> output = imageRecognition.recognizeImage(image);
	    	answer = getAnswer(output);
	    	Log.i(RECOGNITION_TAG, answer);
    	}
    	
    	return answer;
    }
    
    private String getAnswer(HashMap<String, Double> output) {
		double highest = 0;
		String answer = "";
		for (Map.Entry<String, Double> entry : output.entrySet()) {
                    if (entry.getValue() > highest) {
				highest = entry.getValue();
				answer = entry.getKey();
			}
		}

		return answer;
	}
    
    // Carrega rede neural
    private Runnable loadRNA = new Runnable() {

		public void run() {
			// Carrega rede neural
			nnet = NeuralNetwork.load(nnetFile);
			imageRecognition = (ImageRecognitionPlugin) nnet.getPlugin(ImageRecognitionPlugin.class);
		}
		
	};
	
}
